import React, { Component } from 'react'
import axios from 'axios'
import { Table, Switch, Modal, Input, Button, Popconfirm, Form ,Select, message} from 'antd';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';
const { Option } = Select;

export default class index extends Component {
  state = {
    columns: [
      {
        title: '角色名称',
        dataIndex: 'roleName',
        key: 'roleName',
        width: '30%',
        editable: true,
      },
      {
        title: '用户名',
        dataIndex: 'username',
        key: 'username'
      },
      {
        title: '用户状态', 
        dataIndex: 'roleState',
        key: 'roleState',
        render: (data, item) => {  
             {/* 启用禁用用户信息按钮 */}
             return <Switch defaultChecked={data} disabled={item.default} onChange={(checked)=>{this.handleSwitchChange(checked,item)}}></Switch>
        }
      },
      {
        title: '操作',
        dataIndex: '',
        key:'x',
        render: (item) =><div>
          {/* 修改用户信息按钮 */}
          <Button type="primary" shape="circle" icon={<EditOutlined />} disabled={item.default} onClick={() =>this.Update(item,item.roleType)}/>
            &nbsp;
            {/* 删除用户信息按钮 */}
          <Popconfirm title="确定要删除吗?" onConfirm={() => this.handleDelete(item.id)}>
          <Button type="danger" shape="circle" icon={<DeleteOutlined />}disabled={item.default} ></Button>
          </Popconfirm>
        </div>
      }
    ],
    dataList:[],
    visible:false, //添加模态框是否显示
    visibleUpdate:false, //更新模态框是否显示
    roleType:1, //记录选中的roleType-权限等级
    formdata:null  //更新的数据对象
  }
  // 请求数据
  componentDidMount() {
    axios.get("http://localhost:8000/users").then(res =>{
      this.setState({
        dataList:res.data
      })
    })
  }

  // 点击添加用户，模态框出现
  handleAdd = () =>{
    this.setState({
      visible: true
    })
  }
  // 点击确定，模态框隐藏，添加到数据库
  handleOk = () => {
    // 通过ref = addform 获取from表单
    this.refs.addform.validateFields().then(value =>{
      console.log(value);
      this.refs.addform.resetFields(); //重置表单
      axios.post("http://localhost:8000/users",{...value,roleState:false,roleType:this.state.roleType}).then(res =>{
      // 重新设置datalist, 隐藏对话框
      this.setState({
        dataList:[...this.state.dataList,res.data],
        visible: false
      })
    })
    }).catch(info => {
      console.log('Validate Failed:', info);
    });
  }

  // 点击更新用户
  Update = (item,roleType) =>{
    this.setState({
      formdata:item,       //初始化创建的时候赋值
      visibleUpdate: true, // 创建/显示
      roleType:roleType    //要更新的roleType
    })
    // 获取当前username,password,roleName
    var {username,password,roleName} = item
    // 通过ref = updateform 获取from表单,设置默认内容
    this.refs.updateform && this.refs.updateform.setFieldsValue({
      username,
      password,
      roleName
    })
  }
  //更新提交
  handleUpdateOk = ()=>{
   this.refs.updateform.validateFields().then(values =>{
     axios.put(`http://localhost:8000/users/${this.state.formdata.id}`,{
       ...this.state.formdata,
       ...values,
       roleType:this.state.roleType
      }).then( res =>{
        // 深复制，map映射，替换当前id 相等的数据
        var newList = this.state.dataList.map(item =>{
          if(item.id === this.state.formdata.id){
            return res.data
          }else{
            return item
          }
        })
        // 替换后的数组在页面更新,关闭模态框
        this.setState({
          dataList:newList,
          visibleUpdate:false
        })
      })
   }).catch(info => {
    console.log('Validate Failed:', info);
  });
  }

  // 点击Cancel，添加模态框隐藏
  // handleCancel = ()=> {
  //   this.setState({
  //     visible: false,
  //   });
  // }
   // 点击Cancel，更新模态框隐藏
  // handleUpdateCancel = () =>{
  //   this.setState({
  //     visibleUpdate: false,
  //   });
  // }
  // 启用用户
  handleSwitchChange = (checked,item) =>{
    // console.log(checked,item);
    axios.put(`http://localhost:8000/users/${item.id}`,{
      ...item,
      roleState:checked
    }).then(res =>{
      //无需更新页面
    })  
  }

  // 删除用户 - 删除数据库信息，过滤掉当前id信息
  handleDelete = (id) =>{
    axios.delete(`http://localhost:8000/users/${id}`).then(res =>{
      this.setState({
        dataList:this.state.dataList.filter(item =>item.id !== id)
      })
      message.success("删除成功")
    })
  }

  render() {
    return (
      <div>
        <Button onClick={this.handleAdd} type="primary" style={{ marginBottom: 16 }}>
          添加用户
        </Button>
        <Table
          // 表头信息
          columns={this.state.columns}
          // 内容信息
          dataSource={this.state.dataList}
          rowKey={item => {
            return item.id
          }} //设置key值
          pagination={{pageSize:5}}
        />
        {/* 添加用户 */}
        <Modal
          title="添加用户"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={() => {
            this.setState({
                visible: false
            })
        }}
        >
          <Form
            name="basic"
            // 垂直显示
            layout="vertical"
            ref="addform"
          >
            <Form.Item
              label="用户名"
              name="username"
              rules={[{ required: true, message: 'Please input your username!' }]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="密&nbsp;&nbsp;&nbsp;&nbsp;码"
              name="password"
              rules={[{ required: true, message: 'Please input your password!' }]}
            >
              <Input.Password />
            </Form.Item>
            <Form.Item
                name="roleName"
                label="权&nbsp;&nbsp;&nbsp;&nbsp;限"
                rules={[{ required: true, message: 'Please input the roleName of collection!' }]}
            >
              <Select
                showSearch
                optionFilterProp="children"
                onChange={this.onChange}
                // filterOption={(input, option) =>this.getValue(input, option)}
              >
                <Option value="超级管理员">超级管理员</Option>
                <Option value="管理员">管理员</Option>
                <Option value="小编">小编</Option>
              </Select>
            </Form.Item>
          </Form>
        </Modal>
         {/* 修改用户 */}
         <Modal
          title="更新用户"
          visible={this.state.visibleUpdate}
          onOk={this.handleUpdateOk}
          onCancel={() => {
            this.setState({
              visibleUpdate: false
            })
        }}
          >
          <Form
            name="basic2"
            // 垂直显示
            layout="vertical"
            // 输入框显示默认值
            initialValues={this.state.formdata}
            ref="updateform"
          >
            <Form.Item
              label="用户名"
              name="username"
              rules={[{ required: true, message: 'Please input your username!' }]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="密&nbsp;&nbsp;&nbsp;&nbsp;码"
              name="password"
              rules={[{ required: true, message: 'Please input your password!' }]}
            >
              <Input.Password />
            </Form.Item>
            <Form.Item
                name="roleName"
                label="权&nbsp;&nbsp;&nbsp;&nbsp;限"
                rules={[{ required: true, message: 'Please input the roleName of collection!' }]}
            >
              <Select
                showSearch
                optionFilterProp="children"
                onChange={this.onChange}
                // filterOption={(input, option) =>this.getValue(input, option)}
              >
                <Option value="超级管理员">超级管理员</Option>
                <Option value="管理员">管理员</Option>
                <Option value="小编">小编</Option>
              </Select>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    )
  }
  onChange = (data) =>{
    // console.log(data,"根据不同的角色名字，设置好对应的roleType")
    const arr = ["小编","管理员","超级管理员"]
    var roleType = arr.indexOf(data)+1
    this.setState({
      roleType
    })
  }
}
